import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth'
import store from '@/store'

// 创建axios实例
const service = axios.create({
  baseURL: window.VueENV.BASE_API, // api 的 base_url
  timeout: 500000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (!store.state.loading) {
      store.dispatch('toggleLoading',)// { spinner: 'el-icon-loading' }
    }
    const toekn = getToken()
    if (toekn) {
      config.headers.Authorization = 'Bearer ' + toekn
    }
    return config
  },
  error => {
    store.dispatch('toggleLoading', undefined)
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    store.dispatch('toggleLoading', undefined)
    const res = response.data
    if (res.code !== 0) {
      this.message.error(res.msg)

      if (res.code === -2) {
        removeToken()
        setTimeout(() => {
          location.reload()
        }, 3000)
      }
      return Promise.reject(res.msg)
    } else {
      return response.data
    }
  },
  error => {
    store.dispatch('toggleLoading', undefined)
    Promise.reject(error)
  }
)

export default service
